local H = require "packages/new_heg/util"
local U = require "packages/utility/utility"
local extension = Package:new("meritocracy")
extension.extensionName = "new_heg_diy"
extension.game_modes_whitelist = { 'mul_heg_mode', 'ex_heg_mode' }

Fk:loadTranslationTable{
  ["meritocracy"] = "日月交辉·贤",
  ["wk_heg"] = "日月",
}

--- 推举
---@param room Room
---@param player ServerPlayer
---@param skillName string
---@return ServerPlayer?
local function DoElectedChange(room, player, skillName)
  local kingdom = player:getMark("__heg_kingdom")
  if kingdom == "wild" then
    kingdom = player:getMark("__heg_init_kingdom")
  end
  local generals = room:findGenerals(function(g)
    return Fk.generals[g].kingdom == kingdom or Fk.generals[g].subkingdom == kingdom
  end, 1)
  local general = room:askForGeneral(player, generals, 1, true) ---@type string
  room:sendLog{
    type = "#ElectedChangeLog",
    from = player.id,
    arg = general,
    arg2 = skillName,
    toast = true,
  }
  local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end), Util.IdMapper)
  room:sortPlayersByAction(targets)
  local ret
  for _, pid in ipairs(targets) do
    local p = room:getPlayerById(pid)
    local choices = {"Cancel"}
    if p.general ~= "anjiang" and not p.general:startsWith("ld__lord") and not general.subkingdom then
      table.insert(choices, "#elected_change_main:::" .. general)
    end
    if p.deputyGeneral ~= "anjiang" then
      table.insert(choices, "#elected_change_deputy:::" .. general)
    end
    local choice = room:askForChoice(p, choices, "ElectedChange", "#elected_change-ask:" .. player.id .. "::" .. general)
    if choice ~= "Cancel" then
      if choice:startsWith("#elected_change_main") then
        generals = {H.getActualGeneral(p, false)}
        room:changeHero(p, general, false, false, true, false, false)
        room.logic:trigger("fk.GeneralTransformed", p, general)
      else
        generals = {H.getActualGeneral(p, true)}
        room:changeHero(p, general, false, true, true, false, false)
        room.logic:trigger("fk.GeneralTransformed", p, general)
      end
      ret = p
      break
    end
  end
  room:returnToGeneralPile(generals)
  return {ret, general}
end

Fk:loadTranslationTable{
  ["ElectedChange"] = "推举",
  ["#Elected"] = "推举了",
  ["#ElectedChangeLog"] = "%from 由于 “%arg2”，推举了 %arg",
  ["#elected_change_main"] = "选用：将%arg作为主将",
  ["#elected_change_deputy"] = "选用：将%arg作为副将",
  ["#elected_change-ask"] = "%src 推举了 %arg，你可 选用 为你的主将或副将",
}

local chenqun = General(extension, "wk_heg__chenqun", "wei", 3)
local dingpin = fk.CreateTriggerSkill{
  name = "wk_heg__dingpin",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Finish
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return p ~= player end), Util.IdMapper)
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__dingpin-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    room:setPlayerMark(to, "_wk_heg__dingpin", player.id)
    player:turnOver()
    to:gainAnExtraTurn(true, self.name)
  end,
}
local dingpin_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__dingpin_delay",
  events = {fk.EventPhaseStart, fk.TurnEnd},
  anim_type = "special",
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return target.phase == Player.Start and target:getCurrentExtraTurnReason() == "wk_heg__dingpin" 
       and target:getMark("_wk_heg__dingpin") == player.id and H.compareKingdomWith(target, player)
    else
      return target == player and target:getCurrentExtraTurnReason() == "wk_heg__dingpin"
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      room:notifySkillInvoked(player, self.name, "support")
      player:broadcastSkillInvoke(self.name)
      DoElectedChange(room, target, self.name)
    else
      room:setPlayerMark(target, "_wk_heg__dingpin", 0)
      target:turnOver()
    end
  end,
}
dingpin:addRelatedSkill(dingpin_delay)

local faen = fk.CreateTriggerSkill{
  name = "wk_heg__faen",
  anim_type = "offensive",
  events = {fk.TurnedOver, fk.ChainStateChanged},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and H.compareKingdomWith(player, target)) then return false end
    if event == fk.ChainStateChanged then
      return target.chained 
    else
      return (H.hasShownSkill(player, self) or player == target) and target:getHandcardNum() >= 2 and not target.faceup
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.TurnedOver then
      return player.room:askForSkillInvoke(target, self.name, nil, "#wk_heg__faen_turn-invoke")
    else
      return player.room:askForSkillInvoke(player, self.name, nil, "#wk_heg__faen_chained-invoke")
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.TurnedOver then
      -- target:throwAllCards("h")
      player.room:askForDiscard(target, 2, 2, false, self.name, false)
      target:turnOver()
    else
      target:drawCards(1, self.name)
    end
  end,
}
chenqun:addSkill(dingpin)
chenqun:addSkill(faen)

chenqun:addCompanions("hs__n_caopi")
Fk:loadTranslationTable{
  ["wk_heg__chenqun"] = "陈群",
  ["#wk_heg__chenqun"] = "万世臣表",
  ["designer:wk_heg__chenqun"] = "教父&635",

  ["wk_heg__dingpin"] = "定品",
  [":wk_heg__dingpin"] = "结束阶段，你可叠置并令一名其他角色于此回合结束后执行一个额外回合，此额外回合：1.准备阶段，若其与你势力相同，其推举；2.回合结束时，其叠置。<br />" ..
  "<font color = 'gray'>推举：推举角色展示一张与其势力相同的武将牌，每名与其势力相同的角色选择是否将此武将牌替换其已明置的主将或副将。" ..
  "若有角色选择替换，称为该角色<u>选用</u>，停止对后续角色的询问，结束推举流程。</font>",
  ["wk_heg__faen"] = "法恩",
  [":wk_heg__faen"] = "与你势力相同的角色：1.横置后，你可令其摸一张牌；2.叠置后，其可弃置两张手牌，平置。",

  ["@@wk_heg__dingpin_extra"] = "定品",
  ["#wk_heg__dingpin-choose"] = "定品：你可以选择一名其他角色，令其于此回合结束后执行一个额外回合",
  ["#wk_heg__dingpin_delay"] = "定品",

  ["#wk_heg__faen_turn-invoke"] = "法恩：你可以弃置两张手牌，平置",
  ["#wk_heg__faen_chained-invoke"] = "法恩：你可以令其摸一张牌",

  ["$wk_heg__dingpin1"] = "取才赋职，论能行赏。",
  ["$wk_heg__dingpin2"] = "定品寻良骥，中正探人杰。",
  ["$wk_heg__faen1"] = "礼法容情，皇恩浩荡。",
  ["$wk_heg__faen2"] = "法理有度，恩威并施。",
  ["~wk_heg__chenqun"] = "吾身虽陨，典律昭彰。",
}

local caorui = General(extension, "wk_heg__caorui", "wei", 3, 3, General.Male)
local yuchen = fk.CreateTriggerSkill{
  name = "wk_heg__yuchen",
  events = {fk.EventPhaseStart},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and target ~= player and target.phase == Player.Finish and player:getHandcardNum() > 1) then return false end
    return #player.room.logic:getActualDamageEvents(1, function(e)
      return e.data[1].from == target
    end, Player.HistoryTurn) == 0
  end,
  on_cost = function (self, event, target, player, data)
    local cards = player.room:askForCard(player, 2, 2, false, self.name, true, ".", "#wk_heg__yuchen-give")
    if #cards == 2 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:obtainCard(target, self.cost_data, false, fk.ReasonGive)
    if not target.dead then
      room:setPlayerMark(target, "@@wk_heg__yuchen-turn", 1)
      target:gainAnExtraPhase(Player.Play)
    end
  end
}

local yuchen_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__yuchen_delay",
  events = {fk.EventPhaseEnd},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (target:getMark("@@wk_heg__yuchen-turn") > 0 and target.phase == Player.Play and player:usedSkillTimes(yuchen.name, Player.HistoryTurn) > 0 and player:isAlive()) then return false end
    return #player.room.logic:getActualDamageEvents(1, function(e)
      return e.data[1].from == target
    end, Player.HistoryPhase) == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:damage{
      from = player,
      to = target,
      damage = 1,
      skillName = self.name,
    }
  end,
}

local mingsong = fk.CreateTriggerSkill{
  name = "wk_heg__mingsong",
  events = {fk.DamageCaused},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and target and H.compareKingdomWith(player, target)) then return false end
    local cards = table.simpleClone(target:getEquipments(Card.SubtypeWeapon))
    local targets = {}
    if #cards > 0 then
      for _, id in ipairs(cards) do
        for _, q in ipairs(player.room:getOtherPlayers(target)) do
          if target:canMoveCardInBoardTo(q, id) then
            table.insertIfNeed(targets, q.id)
          end
        end
      end
    end
    if #targets > 0 then
      self.cost_data = targets
      return true
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = self.cost_data
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__mingsong-ask::"..target.id, self.name, true)
    if #tos > 0 then
      self.cost_data = tos[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local excludeIds = table.filter(target:getCardIds("e"), function (id) return Fk:getCardById(id).sub_type ~= Card.SubtypeWeapon end)
    room:askForMoveCardInBoard(player, target, to, self.name, "e", target, excludeIds)
    local targets = {}
    local num = 999
    for _, p in ipairs(room.alive_players) do
      local n = p.hp
      if n <= num then
        if n < num then
          num = n
          targets = {}
        end
        if n < p.maxHp then
          table.insert(targets, p.id)
        end
      end
    end
    if #targets > 0 then
      local to_heal = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__mingsong-choose", self.name, true)
      if #to_heal > 0 then
        room:recover{
          who = room:getPlayerById(to_heal[1]),
          num = 1,
          recoverBy = player,
          skillName = self.name,
        }
      end
    end
    return true
  end,
}

caorui:addSkill(yuchen)
yuchen:addRelatedSkill(yuchen_delay)
caorui:addSkill(mingsong)
Fk:loadTranslationTable{
  ["wk_heg__caorui"] = "曹叡",
  ["#wk_heg__caorui"] = "天资的明君",
  ["designer:wk_heg__caorui"] = "小曹神",

  ["wk_heg__yuchen"] = "驭臣",
  [":wk_heg__yuchen"] = "其他角色的结束阶段，若其本回合未造成过伤害，你可交给其两张手牌，令其执行一个额外的出牌阶段，若如此做，此额外的阶段结束时，若其于此阶段未造成过伤害，你对其造成1点伤害。",
  ["wk_heg__mingsong"] = "明讼",
  [":wk_heg__mingsong"] = "与你势力相同的角色造成伤害时，你可移动其装备区里的一张武器牌，防止此伤害，然后你可令一名体力值最小的角色回复1点体力。",

  ["@@wk_heg__yuchen-turn"] = "驭臣",
  ["#wk_heg__yuchen_delay"] = "驭臣",

  ["#wk_heg__yuchen-give"] = "驭臣：你可交给其两张手牌，令其执行一个额外的出牌阶段",
  ["#wk_heg__mingsong-ask"] = "明讼：你可选择一名角色，将 %dest 装备区内的一张武器牌移动至其装备区内，<br />防止此伤害并令一名体力值最小的角色回复1点体力",
  ["#wk_heg__mingsong-choose"] = "明讼：你可令一名体力值最小的角色回复1点体力",

  ["$wk_heg__yuchen1"] = "大展宏图，就在今日。",
  ["$wk_heg__yuchen2"] = "复我大魏，扬我国威。",
  ["$wk_heg__mingsong1"] = "你我推心置腹，岂能相负。",
  ["$wk_heg__mingsong2"] = "孰忠孰奸，朕尚能明辨。",
  ["~wk_heg__caorui"] = "悔不该耽于逸乐，至由今日。",
}

local xujing = General(extension, "wk_heg__xujing", "shu", 3, 3, General.Male)
local yuyan = fk.CreateTriggerSkill{
  name = "wk_heg__yuyan",
  anim_type = "support",
  events = {fk.AfterCardsMove},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) or player.room.current == player then return end
    local n = 0
    for _, move in ipairs(data) do
      if move.to and move.to == player.id and move.from and move.from ~= player.id and move.toArea == Card.PlayerHand then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
            n = n + 1
          end
        end
      end
    end
    if n > 0 then
      self.cost_data = n
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local current = room.current
    local n = self.cost_data
    local cards2
    if #player:getCardIds("he") <= n then
      cards2 = player:getCardIds("he")
    else
      cards2 = room:askForCard(player, n, n, true, self.name, false, ".",
        "#wk_heg__yuyan-give::"..current.id..":"..n)
    end
    room:moveCardTo(cards2, Card.PlayerHand, current, fk.ReasonGive, self.name, nil, false, player.id)
  end,
}
local yuyan_alliance = H.CreateAllianceSkill{
  name = "#wk_heg__yuyan_alliance",
  allow_alliance = function(self, from, to)
    return H.compareKingdomWith(from, to) and to:hasShownSkill(yuyan) and from:distanceTo(to) == 1
  end
}
local yuyan_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__yuyan_delay",
  events = {fk.TurnEnd},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:usedSkillTimes(yuyan.name, Player.HistoryTurn) > 0 and H.compareKingdomWith(player, player.room.current)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    -- if player:isWounded() and not player.dead then
    --   player.room:recover{
    --     who = player,
    --     num = 1,
    --     recoverBy = player,
    --     skillName = self.name,
    --   }
    -- else
    DoElectedChange(player.room, player, self.name)
    -- end
  end,
}

local caixia_filter = fk.CreateActiveSkill{
  name = "#wk_heg__caixia_filter",
  min_card_num = 1,
  max_card_num = 99,
  card_filter = function(self, to_select, selected)
    return table.every(selected, function(id)
      return Fk:getCardById(to_select).trueName == Fk:getCardById(id).trueName
    end) and Fk:currentRoom():getCardArea(to_select) == Player.Hand
  end,
  target_filter = Util.FalseFunc,
  can_use = Util.FalseFunc,
}
local caixia = fk.CreateTriggerSkill{
  name = "wk_heg__caixia",
  anim_type = "defensive",
  events = {fk.Damaged, fk.Damage},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local result, dat = room:askForUseActiveSkill(player, "#wk_heg__caixia_filter", "#wk_heg__caixia", true)
    if result then
      self.cost_data = dat.cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player:showCards(self.cost_data)
    if not player.dead then
      player:drawCards(math.min(#self.cost_data, player.hp), self.name)
    end
  end,
}

yuyan:addRelatedSkill(yuyan_delay)
yuyan:addRelatedSkill(yuyan_alliance)
xujing:addSkill(yuyan)
caixia:addRelatedSkill(caixia_filter)
xujing:addSkill(caixia)
xujing:addCompanions("ld__n_fazheng")
Fk:loadTranslationTable{
  ["wk_heg__xujing"] = "许靖",
  ["#wk_heg__xujing"] = "尺瑜寸瑕",
  ["designer:wk_heg__xujing"] = "教父&635&二四",

  ["wk_heg__yuyan"] = "誉言",
  [":wk_heg__yuyan"] = "①你是与你势力相同且距离为1角色“合纵”的合法目标；②当你于回合外获得其他角色的牌后，你可将等量张牌交给当前回合角色，若如此做，此回合结束时，若其与你势力相同，你推举。<br />"..
    "<font color = 'gray'>推举：推举角色展示一张与其势力相同的武将牌，每名与其势力相同的角色选择是否将此武将牌替换其已明置的主将或副将。" ..
  "若有角色选择替换，称为该角色<u>选用</u>，停止对后续角色的询问，结束推举流程。</font>",
  ["wk_heg__caixia"] = "才瑕",
  [":wk_heg__caixia"] = "每回合限一次，当你造成或受到伤害后，你可展示任意张同名手牌，然后摸等量的牌（至多摸你体力值张）。",

  ["#wk_heg__yuyan-give"] = "誉言：交给 %dest 共计 %arg 张牌",
  ["#wk_heg__yuyan_delay"] = "誉言",
  ["#wk_heg__caixia_filter"] = "才瑕",
  ["#wk_heg__caixia"] = "才瑕：你可以展示任意张同名手牌，然后摸等量的牌。",

  ["$wk_heg__yuyan1"] = "君满腹才学，当为国之大器。",
  ["$wk_heg__yuyan2"] = "一腔青云之志，正待梦日之时。",
  ["$wk_heg__caixia1"] = "吾习扫天下之术，不善净一屋之秽。",
  ["$wk_heg__caixia2"] = "玉有十色五光，微瑕难掩其瑜。",
  ["~wk_heg__xujing"] = "时人如江鲫，所逐者功利尔…",
}

local zhangsong = General(extension, "wk_heg__zhangsong", "shu", 3)
local qiangzhi = fk.CreateTriggerSkill{
  name = "wk_heg__qiangzhi",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and target.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
      return not p:isKongcheng() end), Util.IdMapper)
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__qiangzhi-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name, 1)
    room:notifySkillInvoked(player, self.name, "control")
    local to = room:getPlayerById(self.cost_data)
    room:doIndicate(player.id, {self.cost_data})
    local cards1 = room:askForCardsChosen(player, to, 1, 99, "h", self.name)
    to:showCards(cards1)

    local cards2 = player:getCardIds(Player.Hand)
    player:showCards(cards2)
    room:delay(300)

    local suit = {}
    for _, cid in ipairs(cards2) do
      local card = Fk:getCardById(cid)
      if not table.contains(suit, card.suit) then
        table.insert(suit, card.suit)
      end
    end
    local all_contain = true
    local card_name = {}
    for _, cid in ipairs(cards1) do
      local card = Fk:getCardById(cid)
      if not table.contains(suit, card.suit) then
        all_contain = false
        break
      end
      if not table.contains(card_name, card.name) then
        table.insert(card_name, card.name)
      end
    end
    if all_contain == true then
      room:setPlayerMark(target, "wk_heg__liance-phase", card_name)
      local success, dat = player.room:askForUseActiveSkill(target, "#wk_heg__liance_viewas", "#wk_heg__liance-choose", true)
      if success then 
        local card = Fk.skills["#wk_heg__liance_viewas"]:viewAs(card_name.cards)
          room:useCard{
          from = target.id,
          tos = table.map(dat.targets, function(id) return {id} end),
          card = card,
        }
      end
    end
  end,
}

local xiantu = fk.CreateTriggerSkill{
  name = "wk_heg__xiantu",
  mute = true,
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(self) and target.phase == Player.Play and not target.dead
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local cards = room:askForCard(player, 2, 2, true, self.name, true, ".", "#wk_heg__xiantu-give::"..target.id)
    if #cards == 2 then 
      self.cost_data = cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name, 1)
    room:doIndicate(player.id, {target.id})
    room:moveCardTo(self.cost_data, Player.Hand, target, fk.ReasonGive, self.name, nil, false, player.id)
    room:setPlayerMark(player, "xiantu-phase", 1)
  end,
}

local xiantu_trigger = fk.CreateTriggerSkill{
  name = "#wk_heg__xiantu_trigger",
  mute = true,
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target ~= player and target.phase == Player.Play and player:getMark("xiantu-phase") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if #player.room.logic:getEventsOfScope(GameEvent.Death, 1, function(e)
          local death = e.data[1]
          return death.damage and death.damage.from == target
        end, Player.HistoryPhase) == 0 then
      player:broadcastSkillInvoke("wk_heg__xiantu", 2)
      room:notifySkillInvoked(player, "wk_heg__xiantu", "negative")
      room:loseHp(player, 1, self.name)
    else
      player:broadcastSkillInvoke("wk_heg__xiantu", 1)
      room:notifySkillInvoked(player, "wk_heg__xiantu", "positive")
      player:drawCards(2, self.name)
      room:handleAddLoseSkills(player, "-wk_heg__xiantu", nil)
    end
  end,
}

zhangsong:addCompanions("ld__n_fazheng")
xiantu:addRelatedSkill(xiantu_trigger)
zhangsong:addSkill(qiangzhi)
zhangsong:addSkill(xiantu)
Fk:loadTranslationTable{
  ["wk_heg__zhangsong"] = "张松",
  ["#wk_heg__zhangsong"] = "怀璧待凤仪",
  ["designer:wk_heg__zhangsong"] = "教父&祭祀&猪&边缘",
  ["wk_heg__qiangzhi"] = "强识",
  [":wk_heg__qiangzhi"] = "结束阶段，你可展示一名其他角色任意张手牌，然后你展示所有手牌，若包含其展示的所有花色，你可视为使用其展示的一张基本牌或普通锦囊牌。",
  ["wk_heg__xiantu"] = "献图",
  [":wk_heg__xiantu"] = "其他角色的出牌阶段开始时，你可交给其两张牌，若如此做，此阶段结束时，若其于此回合内杀死过角色，你摸两张牌并失去此技能，否则你失去1点体力。",

  ["#wk_heg__xiantu-give"] = "献图：选择交给 %dest 的两张牌",
  ["#wk_heg__xiantu_trigger"] = "献图",

  ["$wk_heg__qiangzhi1"] = "容我过目，即刻咏来。",
  ["$wk_heg__qiangzhi2"] = "文书强识，才可博于运筹。",
  ["$wk_heg__xiantu1"] = "将军莫虑，且看此图。",
  ["$wk_heg__xiantu2"] = "我已诚心相献，君何踌躇不前？",
  ["~wk_heg__zhangsong"] = "皇叔不听吾谏言，悔时晚矣！",
}

local buzhi = General(extension, "wk_heg__buzhi", "wu", 4)
buzhi.deputyMaxHpAdjustedValue = -1
local hongde = fk.CreateTriggerSkill{
  name = "wk_heg__hongde",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and #player:getCardIds("he") > 0 and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 then
      for _, move in ipairs(data) do
        if #move.moveInfo > 1 and ((move.from == player.id and move.to ~= player.id) or
          (move.to == player.id and move.toArea == Card.PlayerHand)) then
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(room:getOtherPlayers(player), Util.IdMapper)
    local tos, id = room:askForChooseCardAndPlayers(player, targets, 1, 1, ".", "#wk_heg__hongde-give", self.name, false)
    room:obtainCard(tos[1], id, false, fk.ReasonGive)
    -- if not player.dead then
    --   player:drawCards(1, self.name)
    -- end
  end,
}

local shucai = fk.CreateTriggerSkill{
  name = "wk_heg__shucai",
  relate_to_place = 'd',
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and player.phase == Player.Finish and #player:getCardIds("e") > 0 and
      table.find(player.room.alive_players, function(p) return player:canMoveCardsInBoardTo(p, "e") end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p)
      return player:canMoveCardsInBoardTo(p, "e")
    end), Util.IdMapper)
    targets = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__shucai-ask", self.name, true)
    if #targets > 0 then
      self.cost_data = targets[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    target = room:getPlayerById(self.cost_data)
    room:askForMoveCardInBoard(player, player, target, self.name, "e", player)
    if player.dead or target.dead then return end
    DoElectedChange(room, player, self.name)
    if not player.dead and player.deputyGeneral == "wk_heg__buzhi" then
      room:setPlayerMark(player, "wk_heg__dingpan_notagged", 1)
      room:handleAddLoseSkills(player, "-wk_heg__shucai|wk_heg__shucai_notag|wk_heg__dingpan_notag", nil)
    end
  end,
}
local dingpan = fk.CreateActiveSkill{
  name = "wk_heg__dingpan",
  relate_to_place = 'm',
  anim_type = "offensive",
  can_use = function(self, player)
    local room = Fk:currentRoom()
    local n = 0
    for _, p in ipairs(room.alive_players) do
      if p.kingdom == "wild" then
        n = n + 1
      end
    end
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < n + 1
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and
      (not H.compareKingdomWith(Fk:currentRoom():getPlayerById(to_select), Self))
  end,
  target_num = 1,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    target:drawCards(1, self.name)
    local n = target:getAttackRange()
    local choices = {"wk_heg__dingpan_use:"..effect.from}
    if n <= #target:getCardIds("he") then
      table.insert(choices, "#wk_heg__dingpan_give:::"..n)
    end
    local choice = room:askForChoice(target, choices, self.name)
    if choice:startsWith("wk_heg__dingpan_use") then
      room:useVirtualCard("slash", nil, player, target, self.name, true)
    else
      local cards = room:askForCardsChosen(target, target, n, n, "he", self.name)
      room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonGive, self.name, nil, false, player.id)
    end
  end,
}

local shucai_notag = fk.CreateTriggerSkill{
  name = "wk_heg__shucai_notag",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  main_skill = shucai, -- 绷
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and player.phase == Player.Finish and #player:getCardIds("e") > 0 and
      table.find(player.room.alive_players, function(p) return player:canMoveCardsInBoardTo(p, "e") end) and player:usedSkillTimes(self.main_skill.name, Player.HistoryPhase) == 0 -- 假装是一个技能
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p)
      return player:canMoveCardsInBoardTo(p, "e")
    end), Util.IdMapper)
    targets = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__shucai-ask", self.name, true)
    if #targets > 0 then
      self.cost_data = targets[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    target = room:getPlayerById(self.cost_data)
    room:askForMoveCardInBoard(player, player, target, self.name, "e", player)
    if player.dead or target.dead then return end
    DoElectedChange(room, player, self.name)
  end,
}
local shucai_retag = fk.CreateTriggerSkill{
  name = "#wk_heg__shucai_retag",
  events = {fk.EnterDying},
  mute = true,
  can_trigger = function (self, event, target, player, data)
    return player == target and player:getMark("wk_heg__dingpan_notagged") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player.room:handleAddLoseSkills(player, "-wk_heg__shucai_notag|-wk_heg__dingpan_notag|wk_heg__shucai", nil)
  end,
}
shucai_notag:addRelatedSkill(shucai_retag)
local dingpan_notag = fk.CreateActiveSkill{
  name = "wk_heg__dingpan_notag",
  anim_type = "offensive",
  main_skill = dingpan,
  can_use = function(self, player)
    local room = Fk:currentRoom()
    local n = 0
    for _, p in ipairs(room.alive_players) do
      if p.kingdom == "wild" then
        n = n + 1
      end
    end
    return player:usedSkillTimes(self.main_skill.name, Player.HistoryPhase) < n + 1 -- 绷
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and
      (not H.compareKingdomWith(Fk:currentRoom():getPlayerById(to_select), Self))
  end,
  target_num = 1,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    target:drawCards(1, self.name)
    local n = target:getAttackRange()
    local choices = {"wk_heg__dingpan_use:"..effect.from}
    if n <= #target:getCardIds("he") then
      table.insert(choices, "#wk_heg__dingpan_give:::"..n)
    end
    local choice = room:askForChoice(target, choices, self.name)
    if choice:startsWith("wk_heg__dingpan_use") then
      room:useVirtualCard("slash", nil, player, target, self.name, true)
    else
      local cards = room:askForCardsChosen(target, target, n, n, "he", self.name)
      room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonGive, self.name, nil, false, player.id)
    end
  end,
}

buzhi:addSkill(hongde)
buzhi:addSkill(shucai)
buzhi:addSkill(dingpan)
Fk:addSkill(shucai_notag)
Fk:addSkill(dingpan_notag)
Fk:loadTranslationTable{
  ["wk_heg__buzhi"] = "步骘",
  ["#wk_heg__buzhi"] = "博研沈深",
  ["designer:wk_heg__buzhi"] = "教父&风箫",

  ["wk_heg__hongde"] = "弘德",
  [":wk_heg__hongde"] = "每回合限一次，当你一次性获得或失去两张牌后，你可交给一名其他角色一张牌。",
  ["wk_heg__dingpan"] = "定叛",
  [":wk_heg__dingpan"] = "主将技，出牌阶段限X次，你可令一名其他势力角色摸一张牌，然后其选择：1.交给你其攻击范围数张牌；2.你视为对其使用一张【杀】（X为野心家角色数+1）。",
  ["wk_heg__shucai"] = "疏才",
  [":wk_heg__shucai"] = "副将技，此武将牌上单独的阴阳鱼个数-1；结束阶段，你可将你装备区内一张牌移动至其他角色装备区内，然后推举并删除此武将牌所有技能标签至你进入濒死状态。<br />"..
  "<font color = 'gray'>推举：推举角色展示一张与其势力相同的武将牌，每名与其势力相同的角色选择是否将此武将牌替换其已明置的主将或副将。" ..
  "若有角色选择替换，称为该角色<u>选用</u>，停止对后续角色的询问，结束推举流程。</font>",

  ["#wk_heg__hongde-give"] = "弘德：选择一名其他角色，交给其一张牌",
  ["#wk_heg__shucai-ask"] = "疏才：你可选择一名其他角色，将装备区内一张牌移动至其装备区内",
  ["wk_heg__dingpan_use"] = "视为%src对你使用【杀】",
  ["#wk_heg__dingpan_give"] = "交出%arg张牌",
  ["#wk_heg__shucai_retag"] = "疏才",

  ["wk_heg__dingpan_notag"] = "定叛",
  [":wk_heg__dingpan_notag"] = "出牌阶段限X次，你可令一名其他势力角色摸一张牌，然后其选择：1.交给你其攻击范围数张牌；2.你视为对其使用一张【杀】（X为野心家角色数+1）。",
  ["wk_heg__shucai_notag"] = "疏才",
  [":wk_heg__shucai_notag"] = "结束阶段，你可将你装备区内一张牌移动至其他角色装备区内，然后推举并删除此武将牌所有技能标签至你进入濒死状态。<br />"..
  "<font color = 'gray'>推举：推举角色展示一张与其势力相同的武将牌，每名与其势力相同的角色选择是否将此武将牌替换其已明置的主将或副将。" ..
  "若有角色选择替换，称为该角色<u>选用</u>，停止对后续角色的询问，结束推举流程。</font>",

  ["$wk_heg__hongde1"] = "江南重义，东吴尚德。",
  ["$wk_heg__hongde2"] = "德无单行，福必双至。",
  ["$wk_heg__dingpan1"] = "从孙者生，从刘者死！",
  ["$wk_heg__dingpan2"] = "多行不义必自毙！",
  ["$wk_heg__shucai1"] = "督军之才，子明强于我甚多。",
  ["$wk_heg__shucai2"] = "此间重任，公卿可担之。",
  ["~wk_heg__buzhi"] = "交州已定，主公尽可放心。",
}

local luji = General(extension, "wk_heg__luji", "wu", 3, 3, General.Male)
local huaiju = fk.CreateTriggerSkill{
  name = "wk_heg__huaiju",
  events = {fk.CardUseFinished},
  anim_type = "special",
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and not H.compareKingdomWith(player, target) and data.tos and
    table.find(TargetGroup:getRealTargets(data.tos), function(id) return id == player.id end)) then return false end
    return not data.card.is_damage_card and table.every(Card:getIdList(data.card), function (id) return player.room:getCardArea(id) == Card.Processing end)
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return p ~= target end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__huaiju_choose", self.name, true)
    if #tos > 0 then
      self.cost_data = tos[1]
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local card_ids = Card:getIdList(data.card)
    if #card_ids == 0 then return false end
    room:moveCardTo(card_ids, Player.Hand, room:getPlayerById(self.cost_data), fk.ReasonPrey, self.name, nil, true, player.id)
    local choices = {"Cancel"}
    if player:isAlive() and #player:getCardIds("he") > 0 then
      table.insert(choices, "#wk_heg__huaiju_discard_choose::" .. player.id)
    end
    local choice = room:askForChoice(target, choices, self.name)
    if choice ~= "Cancel" then
      local cid = room:askForCardChosen(target, player, "he", self.name)
      room:throwCard({cid}, self.name, player, target)
    end
  end,
}

local zhenglun = fk.CreateTriggerSkill{
  name = "wk_heg__zhenglun",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, self.name)
    player:showCards(player:getCardIds(Player.Hand))
    while true do
      local cards = player.player_cards[Player.Hand]
      -- player:showCards(cards)
      local suits = {}
      for _, id in ipairs(cards) do
        local suit = Fk:getCardById(id).suit
        if suit ~= Card.NoSuit then
          table.insertIfNeed(suits, suit)
        end
      end
      if player:getHandcardNum() > #room.alive_players or #suits == 4 then
        room:delay(1000)
        player:showCards(cards) -- 睿智
        break
      else
        room:delay(500)
        player:drawCards(1, self.name)
      end
    end
    local suitMapper = { [1] = {}, [2] = {}, [3] = {}, [4] = {} }
    table.forEach(player:getCardIds(Player.Hand), function(id)
      if Fk:getCardById(id).suit ~= Card.NoSuit then
        table.insert(suitMapper[Fk:getCardById(id).suit], id)
      end
    end)
    local maxNum = -1
    local all_suits = {"log_spade", "log_club", "log_heart", "log_diamond"}
    local choices = {}
    for i, j in ipairs(suitMapper) do
      local num = #j
      if num >= maxNum then
        if num > maxNum then
          maxNum = num
          choices = {}
        end
        table.insert(choices, all_suits[i])
      end
    end
    local choice = room:askForChoice(player, choices, self.name, "#wk_heg__zhenglun-discard")
    local cid = suitMapper[table.indexOf(all_suits, choice)]
    room:throwCard(cid, self.name, player, player)
  end,
}

luji:addSkill(huaiju)
luji:addSkill(zhenglun)
Fk:loadTranslationTable{
  ["wk_heg__luji"] = "陆绩",
  ["designer:wk_heg__luji"] = "静谦",
  ["#wk_heg__luji"] = "孝淳博识",

  ["wk_heg__huaiju"] = "怀橘",
  [":wk_heg__huaiju"] = "其他势力角色的指定你为目标的非伤害牌结算后，你可令一名除使用者外的角色获得此牌，然后此牌使用者可弃置你一张牌。",
  ["wk_heg__zhenglun"] = "整论",
  [":wk_heg__zhenglun"] = "结束阶段，你可摸一张牌，然后若你手牌数大于存活角色数或其中包含四种花色，则你展示所有手牌并弃置手牌中数量最多的一种花色的所有牌，否则你重复此流程。",

  ["#wk_heg__huaiju_choose"] = "怀橘：你可以将此牌交给一名除使用者外的角色",
  ["#wk_heg__huaiju_discard_choose"] = "弃置 %dest 的一张牌",
  ["#wk_heg__zhenglun-discard"] = "整论：弃置手牌中数量最多的一种花色的所有牌",

  ["$wk_heg__huaiju1"] = "情深舐犊，怀拙藏橘。",
  ["$wk_heg__huaiju2"] = "袖中怀绿橘，遗母报乳哺。",
  ["$wk_heg__zhenglun1"] = "遗失礼仪，则具非议。",
  ["$wk_heg__zhenglun2"] = "行遗礼之举，于不敬王者。",
  ["~wk_heg__luji"] = "恨不能见，车同轨，书同文…",
}

local simahui = General(extension, "wk_heg__simahui", "qun", 3, 3, General.Male)
local jianjie = fk.CreateTriggerSkill{
  name = "wk_heg__jianjie",
  events = {fk.GeneralRevealed},
  anim_type = "special",
  can_trigger = function (self, event, target, player, data)
    if player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and player:hasSkill(self) then
      for _, v in pairs(data) do
        if table.contains(Fk.generals[v]:getSkillNameList(), self.name) then return true end
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, self.name, "support")
    player:broadcastSkillInvoke(self.name)
    for i = 1, 2, 1 do
      local p_table = DoElectedChange(room, player, self.name)
      if p_table then 
        local p_player = p_table[1]
        local p_general = p_table[2]
        if i == 1 and p_player then
          room:setPlayerMark(p_player, "@wk_heg__jianjie1", p_general)
          room:handleAddLoseSkills(p_player, "wk_heg__huoji", nil)
        elseif i == 2 and p_player then
          room:setPlayerMark(p_player, "@wk_heg__jianjie2", p_general)
          room:handleAddLoseSkills(p_player, "wk_heg__lianhuan", nil)
        end
      end
    end
  end,
}

local jianjie_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__jianjie_delay",
  events = {fk.AfterSkillEffect},
  anim_type = "special",
  can_trigger = function (self, event, target, player, data)
    if player == target and target:getMark("@wk_heg__jianjie2") ~= 0 then
      local general2 = target:getMark("@wk_heg__jianjie2")
      return table.contains(Fk.generals[general2]:getSkillNameList(), data.name)
    end
    if player == target and target:getMark("@wk_heg__jianjie1") ~= 0 then
      local general1 = target:getMark("@wk_heg__jianjie1")
      return table.contains(Fk.generals[general1]:getSkillNameList(), data.name)
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local general1 = target:getMark("@wk_heg__jianjie1")
    local general2 = target:getMark("@wk_heg__jianjie2")
    if general1 ~= 0 and table.contains(Fk.generals[general1]:getSkillNameList(), data.name) then
      room:setPlayerMark(target, "@wk_heg__jianjie1", 0)
      room:handleAddLoseSkills(target, "-wk_heg__huoji")
    end
    if general2 ~= 0 and table.contains(Fk.generals[general2]:getSkillNameList(), data.name) then
      room:setPlayerMark(target, "@wk_heg__jianjie2", 0)
      room:handleAddLoseSkills(target, "-wk_heg__lianhuan")
    end
  end,
}

local jingqi = fk.CreateTriggerSkill{
  name = "wk_heg__jingqi",
  events = {fk.Damage, fk.ChainStateChanged},
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0) then return false end
    if event == fk.Damage then
      return data.damageType ~= fk.NormalDamage
    else
      return target.chained
    end
  end,
  on_use = function(self, event, target, player, data)
    if not player.room.current.dead then
      player.room.current:drawCards(1, self.name)
    end
    if not player.dead and player ~= player.room.current then
      player:drawCards(1, self.name)
    end
  end
}

local wk_heg__huoji = fk.CreateViewAsSkill{
  name = "wk_heg__huoji",
  anim_type = "offensive",
  pattern = "fire_attack",
  prompt = "#huoji",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).color == Card.Red and Fk:currentRoom():getCardArea(to_select) ~= Player.Equip
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("fire_attack")
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
}

local wk_heg__lianhuan = fk.CreateActiveSkill{
  name = "wk_heg__lianhuan",
  mute = true,
  card_num = 1,
  min_target_num = 0,
  prompt = "#hs__n_lianhuan",
  can_use = function(self, player)
    return not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected, player)
    return #selected == 0 and Fk:getCardById(to_select).suit == Card.Club and table.contains(player:getHandlyIds(true), to_select)
  end,
  target_filter = function(self, to_select, selected, selected_cards, _, _, player)
    if #selected_cards == 1 then
      local card = Fk:cloneCard("iron_chain")
      card:addSubcard(selected_cards[1])
      card.skillName = self.name
      return player:canUse(card) and card.skill:targetFilter(to_select, selected, selected_cards, card, nil, player) and
      not player:prohibitUse(card) and not player:isProhibited(Fk:currentRoom():getPlayerById(to_select), card)
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:broadcastSkillInvoke(self.name)
    if #effect.tos == 0 then
      room:notifySkillInvoked(player, self.name, "drawcard")
      room:recastCard(effect.cards, player, self.name)
    else
      room:notifySkillInvoked(player, self.name, "control")
      room:sortPlayersByAction(effect.tos)
      room:useVirtualCard("iron_chain", effect.cards, player, table.map(effect.tos, function(id)
        return room:getPlayerById(id) end), self.name)
    end
  end,
}

simahui:addRelatedSkill(wk_heg__huoji)
simahui:addRelatedSkill(wk_heg__lianhuan)
jianjie:addRelatedSkill(jianjie_delay)
simahui:addSkill(jianjie)
simahui:addSkill(jingqi)
Fk:loadTranslationTable{
  ["wk_heg__simahui"] = "司马徽",
  ["designer:wk_heg__simahui"] = "教父&静谦&猪",
  ["#wk_heg__simahui"] = "水镜先生",

  ["wk_heg__jianjie"] = "荐杰",
  [":wk_heg__jianjie"] = "当你首次明置此武将牌后，你推举两次，以此法第一次/第二次选用的角色获得“火计”/“连环”直至其发动选用武将牌上的技能。<br />"..
  "<font color = 'gray'>推举：推举角色展示一张与其势力相同的武将牌，每名与其势力相同的角色选择是否将此武将牌替换其已明置的主将或副将。" ..
  "若有角色选择替换，称为该角色<u>选用</u>，停止对后续角色的询问，结束推举流程。</font>",
  ["wk_heg__jingqi"] = "经奇",
  [":wk_heg__jingqi"] = "每回合限一次，当一名角色造成属性伤害或横置后，你可与当前回合角色各摸一张牌。",

  ["@wk_heg__jianjie1"] = "荐杰 火计",
  ["@wk_heg__jianjie2"] = "荐杰 连环",
  ["#wk_heg__jianjie_delay"] = "荐杰",

  ["wk_heg__huoji"] = "火计",
  [":wk_heg__huoji"] = "你可将一张红色手牌当【火攻】使用",
  ["wk_heg__lianhuan"] = "连环",
  [":wk_heg__lianhuan"] = "你可将一张♣手牌当【铁索连环】使用或重铸",

  ["$wk_heg__jianjie1"] = "卧龙凤雏，二者得一，可安天下。",
  ["$wk_heg__jianjie2"] = "二人齐聚，汉室可兴。",
  ["$wk_heg__jingqi1"] = "好，很好，非常好！",
  ["$wk_heg__jingqi2"] = "您的话也很好！",
  ["~wk_heg__simahui"] = "这似乎，没那么好了…",
}

-- local liubiao = General(extension, "wk_heg__liubiao", "qun", 4, 4, General.Male)
-- local jujiang = fk.CreateTriggerSkill{
--   name = "wk_heg__jujiang",
--   events = {fk.TargetConfirming},
--   anim_type = "special",
--   can_trigger = function(self, event, target, player, data)
--     return player:hasSkill(self) and player == target and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 
--      and U.isOnlyTarget(target, data, event) and H.compareKingdomWith(player.room:getPlayerById(data.from), player, true)
--   end,
--   on_use = function(self, event, target, player, data)
--     data.tos = AimGroup:initAimGroup({})
--     data.targetGroup = {}
--     local from = player.room:getPlayerById(data.from)
--     player.room:useVirtualCard("befriend_attacking", nil, from, player, self.name, true)
--   end,
-- }

-- -- liubiao:addCompanions("fk_heg__caifuren")
-- liubiao:addCompanions("wk_heg__kuaizi")
-- liubiao:addSkill(jujiang)
-- Fk:loadTranslationTable{
--   ["wk_heg__liubiao"] = "刘表",
--   ["#wk_heg__liubiao"] = "跨蹈汉南",
--   ["designer:wk_heg__liubiao"] = "小曹神",

--   ["wk_heg__jujiang"] = "据疆",
--   [":wk_heg__jujiang"] = "每回合限一次，当你成为与你势力不同的角色使用牌的唯一目标时，你可取消之，然后其视为对你使用一张【远交近攻】。",

--   ["$wk_heg__jujiang1"] = "江河霸主何惧之有！",
--   ["$wk_heg__jujiang2"] = "荆襄之地固若金汤。",
--   ["~wk_heg__liubiao"] = "优柔寡断，要不得啊。",
-- }

local gaogan = General(extension, "wk_heg__gaogan", "qun", 4, 4, General.Male)
local juguan = fk.CreateActiveSkill{
  name = "wk_heg__juguan",
  anim_type = "control",
  card_num = 0,
  target_num = 0,
  prompt = "#wk_heg__juguan",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local targets = table.map(table.filter(room.alive_players, function(p) return player:inMyAttackRange(p) end), Util.IdMapper)
    if #targets > 0 then
      local tos = room:askForChoosePlayers(player, targets, 1, 10, "#wk_heg__juguan_choose", self.name, true)
      for i = 1, #tos, 1 do
        local from = room:getPlayerById(tos[i])
        room:useVirtualCard("duel", nil, from, player, self.name, true)
      end
      local slash_targets = {}
      local draw_num = 0
      if not player.dead then
        for i = 1, #tos, 1 do
          local from = room:getPlayerById(tos[i])
          if from:getMark("wk_heg__juguan_record-phase") == 1 then
            draw_num = draw_num + 1
          elseif not from.dead then
            table.insert(slash_targets, from)
          end
        end
        player:drawCards(draw_num, self.name)
        room:useVirtualCard("slash", nil, player, slash_targets, self.name, true)
      end
    end
  end, 
}

local juguan_record = fk.CreateTriggerSkill{
  name = "#wk_heg__juguan_record",
  anim_type = "control",
  refresh_events = {fk.Damage},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(juguan.name, true) and data.card and data.card.trueName == "duel" and not data.from.dead and table.contains(data.card.skillNames, juguan.name)
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(data.from, "wk_heg__juguan_record-phase", 1)
  end,
}

juguan:addRelatedSkill(juguan_record)
gaogan:addSkill(juguan)
Fk:loadTranslationTable{
  ["wk_heg__gaogan"] = "高干",
  ["#wk_heg__gaogan"] = "",
  ["designer:wk_heg__gaogan"] = "祭祀",

  ["#wk_heg__juguan"] = "拒关：你可以令任意名你攻击范围内的角色依次视为对你使用一张【决斗】",
  ["wk_heg__juguan"] = "拒关",
  [":wk_heg__juguan"] = "出牌阶段限一次，你可以令任意名你攻击范围内的角色依次视为对你使用一张【决斗】，然后你摸X张牌并视为对其中未以此法对你造成伤害的角色使用一张【杀】（X为其中以此法对你造成伤害的角色数）。",

  -- ["@@wk_heg__juguan_record-phase"] = "拒关",
  ["#wk_heg__juguan_choose"] = "拒关：选择你攻击范围内任意名角色，这些角色依次视为对你使用一张【决斗】",

  ["$wk_heg__juguan1"] = "",
  ["$wk_heg__juguan2"] = "",
  ["~wk_heg__gaogan"] = "",
}
return extension
